package com.magima.core.app;

import java.lang.ref.WeakReference;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class BaseFragment extends Fragment {
	protected BaseApplication app;
	private WeakReference<FragmentActivity> mContext;
	protected boolean mIsActivated;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mContext = new WeakReference<FragmentActivity>(getActivity());
		app = BaseApplication.fromContext(getActivity());
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
	@Override
	public void startActivity(Intent intent) {
		Object isForce = app.getData().get(BaseApplication.KEY_FORCE_UPDATE);
		if(isForce == null || !(Boolean)isForce){
			try {
				super.startActivity(intent);
			} catch ( ActivityNotFoundException e) {
				if ( app.getActivityNotFoundExceptionHandler() != null )
					app.getActivityNotFoundExceptionHandler().onException(getMyActivity(), e);
			}
		}
	}
	
	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		Object isForce = app.getData().get(BaseApplication.KEY_FORCE_UPDATE);
		if(isForce == null || !(Boolean)isForce){
			try {
				super.startActivityForResult(intent, requestCode);
			} catch ( ActivityNotFoundException e) {
				if ( app.getActivityNotFoundExceptionHandler() != null )
					app.getActivityNotFoundExceptionHandler().onException(getMyActivity(), e);
			}
		}
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    mIsActivated = true;
	    app.getAnalystsTool().onPageStart(this.getClass().getName());
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    mIsActivated = false;
	    app.getAnalystsTool().onPageEnd(this.getClass().getName());
	}
	
	public FragmentActivity getMyActivity(){
		if ( mContext == null )
			return null;
		return mContext.get();
	}
	
	public boolean isDead(){
		if ( app.isDead() || getMyActivity().isFinishing() )
			return true;
		return false;
	}
}
